#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
    :author: 5km (十里)
    :url: https://www.smslit.top
    :copyright: © 2018 5km <5km@smslit.cn>
    :license: MIT, see LICENSE for more details.
"""
import os
import xlwt
import argparse
import os.path as op


def getArgs():
    '''
    获取命令参数
    '''
    parser = argparse.ArgumentParser(
        description='转换 csv 文件为 xls 文件，或转换指定目录下的所有 csv 文件')
    parser.add_argument(
        'paths', nargs='+', help='指定一个或多个路径，可以是csv文件，也可以是一个目录的路径')
    return parser.parse_args()


def csv2xls_singlefile(filePath):
    '''
    转换单个 csv 文件
    '''
    excel_filename = str(filePath.split(".")[0]) + ".xls"
    print('converting %s to %s ...' % (filePath, excel_filename), end=', ')
    myexcel = xlwt.Workbook(encoding='utf-8')
    mysheet = myexcel.add_sheet("sheet1")
    csvfile = open(filePath, "r")
    csvLines = csvfile.readlines()
    csvfile.close()
    linenum = 0
    for csvLine in csvLines:
        r = 0
        cellList = csvLine.split(",")
        for i in cellList:
            mysheet.write(linenum, r, i)
            r += 1
        linenum += 1
    myexcel.save(excel_filename)
    print('Done!')
    return excel_filename


if __name__ == '__main__':
    args = getArgs()
    for path in args.paths:
        csvFileList = []
        if op.isfile(path):
            if '.csv' in path:
                csv2xls_singlefile(path)
                exit(0)
            else:
                print(path + ' is not a direction and csv file!!!')
                exit(-1)
        else:
            fileList = os.listdir(path)
            for fileName in fileList:
                if '.csv' in fileName:
                    csvFileList.append(fileName)
            if len(csvFileList) == 0:
                print(path + ' has no csv file!')
                exit(0)
            else:
                for csvFile in csvFileList:
                    csv2xls_singlefile(csvFile)
